#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<string.h>

/*
This is func1 thread
1, I got lock2
This is func2 thread
2, I got lock1

两个线程陷入了死锁，解决办法如下：
1. 两个线程都用相同的锁作为第一把锁
 *
 *
 */

pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;

FILE *fp;

void * func1(void * arg){
	printf("This is func1 thread\n");
	char s[] = "I write in func1 thread\n";
	while(1){
		pthread_mutex_lock(&mutex2);
		printf("%d, I got lock2\n", (int)arg);
		sleep(1);
		pthread_mutex_lock(&mutex1);
		printf("%d, I got lock1\n", (int)arg);

		pthread_mutex_unlock(&mutex1);
		pthread_mutex_unlock(&mutex2);
		usleep(1);
	}
}

void * func2(void * arg){	
	printf("This is func2 thread\n");
	char s[] = "I write in func2 thread\n";
	while(1){
		pthread_mutex_lock(&mutex1);
		printf("%d, I got lock1\n", (int)arg);
		sleep(1);
		pthread_mutex_lock(&mutex2);
		printf("%d, I got lock2\n", (int)arg);

		pthread_mutex_unlock(&mutex2);
		pthread_mutex_unlock(&mutex1);
		usleep(1);
	}
}

int main(){
	pthread_t tid1, tid2;
	void * ret;

	//定一个临界资源 ：文件
	fp =  fopen("1.txt", "a+");
	if(fp == NULL){
		perror("fopen");
		return 0;
	}

	//线程1：往文件写
	pthread_create(&tid1, NULL, func1, (void *)1);
	//线程2：往文件写
	pthread_create(&tid2, NULL, func2, (void *)2);

	//不让进程退出
	while(1){
		sleep(1);
	}
}
